// 引入接口文件
import {
  save,
  create,
  down,
  searchAccountingName,
  queryInfo,
  importAccount,
  // getMcrmAdmin,
  ondelete,
  projectFilter,
  queryCheckOut,
  queryApplyDetailLm,
  saveLmHandleUnionBuy,
  queryLmDetail,
  listAssociated,
  startTaskDto,
  lmReChooseList,
  isSyncTheProject,
  queryClueByClueId
  } from './commissionsDistListDetailServ'
  
  // 对象和JSON字符串互转
  import { parse } from 'qs'
  // 弹出消息框
  import { Modal,message } from 'antd'
  // const confirm = Modal.confirm; 
  // 日期处理对象
  // import moment from 'moment'
  /*isEmpty 对象是否为空
   *isArray 对象是否数组
   *cloneDeep 对象深拷贝
   */
  import { isEmpty, isArray, cloneDeep, merge, pick,set,get } from 'lodash'
  // 引入路由对象
  import { hashHistory } from 'dva/router'
  // import { download } from "utils/util"
  import config from 'config/config'
  import $ from 'jquery';
  // 初始默认状态
  const defultState = {
    id: '',
    loading: false,
    uploading: false,
    riskId: '',
    projectFilterParams: [],
    jointData: [],
    houseInfoData: [],
    keys: 3,
    synchronousType: false,
    tableObj: {
      key: '',
      theAmount: 0,
      remark: '',
      buyState: '',
      commissionAmount: 0,
      totalAmount: 0,
      paidAmount: 0,
      acState: '',
      addType: 1
    },
    applyDetailTemIdList: [],
    distributionNameList: [],
    createFaymentMethodFlag: true,
    actionType:'check',
    aurList: [],
    channelIndex:'1',
    imageUrls: [],
    imageUrls1:[],
    funType: '',
    generate: '',
    biz: '',
    biz1: {},
    biz2: {},
    biz3: {},
    biz4: {},
    detail: {
      id: '',
      ruleId: '', //佣金方案id
      ruleName: '',//佣金方案名称
      projectId: '', //项目ID
      projectName: '',//项目名称
      distCoId: '',//分销公司id
      distCoName: '',//分销公司名称
      accountingId: '',//费控核算主体id
      accountingName:'',//费控核算主体
      computeNodes:'',//佣金计算节点
      documentNo: '',//单据号  录入不需要传
      endTime:'',//结束日期
      createTime: '',//登记时间
      createByName:'',//登记人员姓名
      createBy:'',//登记人员id
      theAmount: '',//本次应付佣金总金额
      signNumber:'0',//签约套数
      signAmount:'0',//签约金额
      totalAmount:'0',//费用总金额
      applyReason: '',//申请事由
      remark: '',//备注
      // applyId: '', //原佣金申请单Id
      applyIdList: [],
      applyName: '',//原佣金申请单名称
      buyState: 2,//购房状态(1草签 2网签)
      noCommission:'',//是否特例规则
      paymentMethod: [], //付款方式
      applyDetail: [], //明细
      aur: [],//附件数据
    },
    checkboxData: {
      paymentTypeName:['SD040201','SD040205','SD040208','SD040203','SD040204','SD040207'],
      oneTime: '1',
      hybrid:'0.3',
      noStaff:'0.3',
      business:'0.3',
      reserve: '0.3',
      noStaffAll: '0.3',
    },
    // 表格数据
    tableData: {
      dataSource: [],
      total: 0,
      stop:0,
      start:0
    },
    // 表格分页设置
    pageConfig: {
      pageSize: Number.parseInt(config.smallPageSizeList[0]),
      pageNo: 1
    },
    pageConfig1:{
      pageSize: Number.parseInt(config.smallPageSizeList[0]),
      pageNo: 1
    },
    
    selectedRowKeys: [],
    selectedRows: [],
    selectedRowKeys1: [],
    selectedRows1: [],
    projectModalObj: {
      visible: false,
    },
    distCoNameModalObj:{
      visible: false
    },
    commissionModalObj: {
      visible: false
    },
    oldCommissionModalObj: {
      visible: false
    },
    fileModalObj: {
      visible: false,
    },
    uploadFileObj: {
      visible: false,
    },
    buyHouseModalObj:{
      visible: false,
    },
    buyHouseInfo:{
      visible: false,
    },
    deductionModalObj: {
      visible: false,
      deduction: '',
      deductionInfo: ''
    },
    cluesUpModalObj:{
      visible:false,
      data:{
        name:'',
        mobile:'',
        createTime:'',
        expiredMsg:'',
        expiredTime:'',
        followUpList:[]
      }
    },
    suitableDataList: [],
    applyDataList:[],
    applyDataListObj: {
      dataSource: [],
      total: 0,
      stop:0,
      start:0
    },
    noSuitableDataList: [],
    selectOptionData: [
      { 
        value: '0.1',
        name: "10",
      },
      {
        value: '0.2',
        name: "20",
      },
      {
        value: '0.3',
        name: "30",
      },
      {
        value: '0.4',
        name: "40",
      },
      {
        value: '0.5',
        name: "50",
      },
      {
        value: '0.6',
        name: "60",
      },
      {
        value: '0.7',
        name: "70",
      },
      {
        value: '0.8',
        name: "80",
      },
      {
        value: '0.9',
        name: "90",
      },
      {
        value: '1',
        name: "100",
      }
    ],
    searchData: {
      applyReason: '',
      distCoName: ''
    }
  }
  // 声明module
  const tmpModule = {
    // namespace: 'secondKillingSetting',
    // 默认状态
    state: cloneDeep(defultState),
    // 入口函数(先执行)
    subscriptions: {
      setup({ dispatch, history }) {
        history.listen(({ pathname, query }) => {
          // 页面路由匹配时执行
          if ('' + tmpModule.pathname === '' + pathname) {
            query.id=query.id+''
            dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
            if (query.actionType == 'edit'|| query.actionType == 'check') {
              dispatch({type: 'queryInfo',payload: {actionType: query.actionType,id: query.id, } })
            } else {
              dispatch({type: 'updateStore',payload: {actionType: query.actionType,id: query.id, } })
            }
            dispatch({type: 'projectFilter',payload: {actionType: query.actionType,id: query.id, } })
          } // end if
        }) // end listen
      },
    },
    
    // 方法列表
    effects: {
      * startTaskDto({payload}, {put, call, select}) {
        let {uploading,detail} = yield select(state => state[tmpModule.namespace])
        const cc = new Date().getTime()
        let halfYear = 365 / 2 * 24 * 3600 * 1000;
        let pastResult = cc - halfYear
        let pastDate = new Date(pastResult)
        let pastYear = pastDate.getFullYear()
        let pastMonth = pastDate.getMonth() + 1
        let pastDay = pastDate.getDate()
        let date = pastYear + '-' + pastMonth + '-' + pastDay
        if(!detail.projectId||!detail.ruleId){
          message.warn('必须要有项目和佣金方案,才能同步')
          return
        }
        let params = {
          updateTime: date,
          projectId: detail.projectId,
          ruleId: detail.ruleId
        }
        yield put({type: 'updateStore', payload: {uploading:true}})
        let { msg,success} = yield call(startTaskDto, {...params})
        
      },
      * isSyncTheProject({payload}, {put, call, select}) {
        let {uploading,detail} = yield select(state => state[tmpModule.namespace])
        let params = {
          projectId: detail.projectId,
        }
        let { msg,success} = yield call(isSyncTheProject, params)
        if(success){
          uploading = false
          yield put({type: 'updateStore', payload: {uploading}})
        }
        
      },
      * listAssociated({payload}, {put, call, select}) {
        let {detail,applyDataList,applyDataListObj} = yield select(state => state[tmpModule.namespace])
        let params = {
          projectId: detail.projectId,
          pageSize:'10000',
          pageNo:'1',
          distCoId: detail.distCoId
        }
        let { success, msg, rows } = yield call(listAssociated, {...params})
        if(success){
          applyDataListObj.dataSource = rows
          applyDataList = rows
          yield put({type: 'updateStore', payload: {applyDataListObj,applyDataList}})
        }
      },
      *queryInfo({payload}, {put, call, select}) {
        //查询
        let {selectedRowKeys1,aurList,imageUrls,id,channelIndex,checkboxData,detail,tableData,suitableDataList,noSuitableDataList} = yield select(state => state[tmpModule.namespace])
        let params = {
          id: id
        }
        const {data, success} = yield call(queryInfo,params)
        if(success){
          detail = data
          let tempList = data.applyDetail 
          let tempList2 = data.paymentMethod
          for(var item of data.aur){
            if(item.isDelete == 1){
              let obj = {
                url: item.aliOssUrl,
                name: item.fileName
              }
              imageUrls.push(obj)
              aurList.push(item)
            }
          }
          suitableDataList = []
          noSuitableDataList = []
          for(var item of tempList){
            if(item.acState == '1'){
              suitableDataList.push(item)
             }else{
               noSuitableDataList.push(item)
             }
          }

           if(channelIndex == '1'){
             tableData.dataSource = suitableDataList
           }else{
             tableData.dataSource = noSuitableDataList
           }
           
          checkboxData.paymentTypeName = []
          for(var item of tempList2){
            if(item.paymentTypeCode == 'SD040201'){
              checkboxData.oneTime = item.paymentRatioNum
            }else if(item.paymentTypeCode == 'SD040205'){
              checkboxData.hybrid = item.paymentRatioNum
            }else if(item.paymentTypeCode == 'SD040208'){
              checkboxData.noStaff = item.paymentRatioNum
            }else if(item.paymentTypeCode == 'SD040203'){
              checkboxData.business = item.paymentRatioNum
            }else if(item.paymentTypeCode == 'SD040204'){
              checkboxData.reserve = item.paymentRatioNum
            }else if(item.paymentTypeCode == 'SD040207'){
              checkboxData.noStaffAll = item.paymentRatioNum
            }
            checkboxData.paymentTypeName.push(item.paymentTypeCode)
          }
          if(suitableDataList.length>0){
            let theAmountAll = 0;
            let commissionAmountAll = 0;
            let totalAmountAll = 0;
            let paidAmountAll = 0;
            let commissionAmountRuleAll = 0
            suitableDataList.forEach(({ theAmount, commissionAmount,totalAmount,paidAmount,commissionAmountRule}) => {
              theAmountAll += parseFloat(theAmount);
              commissionAmountAll += parseFloat(commissionAmount);
              totalAmountAll += parseFloat(totalAmount);
              paidAmountAll += parseFloat(paidAmount);
              commissionAmountRuleAll += parseFloat(commissionAmountRule);
            });
            theAmountAll =  Math.round(parseFloat(theAmountAll)*100)/100
            commissionAmountAll = Math.round(parseFloat(commissionAmountAll)*100)/100
            totalAmountAll =  Math.round(parseFloat(totalAmountAll)*100)/100
            paidAmountAll =  Math.round(parseFloat(paidAmountAll)*100)/100
            commissionAmountRuleAll =  Math.round(parseFloat(commissionAmountRuleAll)*100)/100
            let obj ={
              theAmount: theAmountAll,
              commissionAmount: commissionAmountAll,
              totalAmount: totalAmountAll,
              paidAmount: paidAmountAll,
              commissionAmountRule: commissionAmountRuleAll,
              houseArea: '合计',
              id: 999
            }
            suitableDataList.push(obj)
          }
          for(var itt of data.applyIdList){
            selectedRowKeys1.push(itt.applyId2)
          }
          yield put({
            type: 'updateStore',
            payload: {
              tableData,suitableDataList,noSuitableDataList,detail,checkboxData,aurList,imageUrls,selectedRowKeys1
            }
          })
        }
      },
      *create({payload},{put,select,call}){
        //生成客户明细
        let {generate,applyDetailTemIdList,createFaymentMethodFlag,selectedRowKeys,selectedRows,funType,checkboxData,channelIndex,noSuitableDataList,suitableDataList,detail,tableData} = yield select(state => state[tmpModule.namespace])
        yield put({type: 'updateStore', payload: {loading: true,}})
        let tempArr = []
        let paymentMethod = []
        generate = 1
        checkboxData.paymentTypeName.forEach(item => {
          let obj = {
            id:'',
            applyId:'',
          }
          if(item == 'SD040201'){
            obj['paymentTypeCode'] = 'SD040201'
            obj['paymentTypeName'] = '一次性付款'
            obj['paymentRatioNum'] = checkboxData.oneTime
          }else if(item == 'SD040205'){
            obj['paymentTypeCode'] = 'SD040205'
            obj['paymentTypeName'] = '混合贷款'
            obj['paymentRatioNum'] = checkboxData.hybrid
          }else if(item == 'SD040208'){
            obj['paymentTypeCode'] = 'SD040208'
            obj['paymentTypeName'] = '非员工首付分期'
            obj['paymentRatioNum'] = checkboxData.noStaff
          }else if(item == 'SD040203'){
            obj['paymentTypeCode'] = 'SD040203'
            obj['paymentTypeName'] = '商业贷款'
            obj['paymentRatioNum'] = checkboxData.business
          }else if(item == 'SD040204'){
            obj['paymentTypeCode'] = 'SD040204'
            obj['paymentTypeName'] = '公积金按揭'
            obj['paymentRatioNum'] = checkboxData.reserve
          }else if(item == 'SD040207'){
            obj['paymentTypeCode'] = 'SD040207'
            obj['paymentTypeName'] = '非员工全款分期'
            obj['paymentRatioNum'] = checkboxData.noStaffAll
          }
          tempArr.push(obj)
        });
        paymentMethod = detail.paymentMethod?detail.paymentMethod:[]
        for(var item of paymentMethod){
          for(var itemed of tempArr){
            if(item.paymentTypeCode == itemed.paymentTypeCode){
              itemed.id = item.id
              itemed.applyId = item.applyId
            }
          }
        }
        let params = {
          projectId: detail.projectId,
          distCoId: detail.distCoId,
          ruleId: detail.ruleId,
          accountingId: detail.accountingId,
          //  applyId: detail.applyId,
          applyIdList: detail.applyIdList,
          ruleName: detail.ruleName,
          computeNodes: detail.computeNodes,
          noCommission: detail.noCommission,
          buyState: detail.buyState,
          applyDetailTemId: [],
          endTime: detail.endTime,
          PaymentMethod: tempArr,
          distCoName: detail.distCoName,
          id: detail.id,
        }
        const { success, msg, data } = yield call(create, {...params})
        if(success == false){
          yield put({type: 'updateStore', payload: {loading: false,}})
        }
        if(success){
          yield put({type: 'updateStore', payload: {loading: false,}})
          let tempList = data.applyDetail
          if(!tempList.length){
            message.warn('系统查询无符合条件数据')
          }
          suitableDataList = []
          noSuitableDataList = []
          for(var item of tempList){
            if(item.acState == '1'){
              suitableDataList.push(item)
             }else{
               noSuitableDataList.push(item)
             }
          }
          
           if(channelIndex == '1'){
             tableData.dataSource = suitableDataList
           }else{
             tableData.dataSource = noSuitableDataList
           }
           if(suitableDataList.length>0){
             let theAmountAll = 0;
             let commissionAmountAll = 0;
             let totalAmountAll = 0;
             let paidAmountAll = 0;
             let commissionAmountRuleAll = 0
             suitableDataList.forEach(({ theAmount, commissionAmount,totalAmount,paidAmount,commissionAmountRule }) => {
               theAmountAll += parseFloat(theAmount);
               commissionAmountAll += parseFloat(commissionAmount);
               totalAmountAll += parseFloat(totalAmount);
               paidAmountAll += parseFloat(paidAmount);
               commissionAmountRuleAll += parseFloat(commissionAmountRule);
             });
             theAmountAll =  Math.round(parseFloat(theAmountAll)*100)/100
             commissionAmountAll = Math.round(parseFloat(commissionAmountAll)*100)/100
             totalAmountAll =  Math.round(parseFloat(totalAmountAll)*100)/100
             paidAmountAll =  Math.round(parseFloat(paidAmountAll)*100)/100
             commissionAmountRuleAll =  Math.round(parseFloat(commissionAmountRuleAll)*100)/100
             let obj ={
               theAmount: theAmountAll,
               commissionAmount: commissionAmountAll,
               totalAmount: totalAmountAll,
               paidAmount: paidAmountAll,
               commissionAmountRule: commissionAmountRuleAll,
               houseArea: '合计',
               id: 999
             }
             suitableDataList.push(obj)
           }
           
           detail.paymentMethod = data.paymentMethod
           detail.applyDetail = data.applyDetail
           detail.signNumber = data.signNumber
           detail.signAmount = data.signAmount
           detail.theAmount = data.theAmount
           detail.totalAmount = data.totalAmount 
           createFaymentMethodFlag = true
           yield put({
            type: 'updateStore',
            payload: {
              tableData,suitableDataList,noSuitableDataList,detail,createFaymentMethodFlag,generate
            }
          })
        }
      },
      
      *ondelete({payload},{put,select,call}){
        //生成客户明细
        let {applyDetailTemIdList,selectedRowKeys,selectedRows,suitableDataList,detail} = yield select(state => state[tmpModule.namespace])
        applyDetailTemIdList = []
        for(var item of selectedRows){
          if(item.acState== '1'&& !item.addType){
            applyDetailTemIdList.push(item.applyDetailTemId)
            let arr = []
            let arr1 = []
            suitableDataList.map((item, index) => {
              if (selectedRowKeys.indexOf(item.key) == -1) {
                arr.push(item)
              }
            })
            detail.applyDetail.map((item, index) => {
              if (selectedRowKeys.indexOf(item.key) == -1) {
                arr1.push(item)
              }
            })
            suitableDataList = arr
            detail.applyDetail = arr1
            yield put({
              type: 'updateStore',
              payload: {
                suitableDataList,detail
              }
            })
          }else if (item.acState == '1'&& item.acState!== 0 && item.addType == '1'){
            let arr = []
            let arr1 = []
            suitableDataList.map((item, index) => {
              if (selectedRowKeys.indexOf(item.key) == -1) {
                arr.push(item)
              }
            })
            detail.applyDetail.map((item, index) => {
              if (selectedRowKeys.indexOf(item.key) == -1) {
                arr1.push(item)
              }
            })
            suitableDataList = arr
            detail.applyDetail = arr1
            yield put({
              type: 'updateStore',
              payload: {
                suitableDataList,detail
              }
            })
            return false
          }
        }

        if(suitableDataList.length>0){
          suitableDataList.pop()
          let theAmountAll = 0;
          let commissionAmountAll = 0;
          let totalAmountAll = 0;
          let paidAmountAll = 0;
          let commissionAmountRuleAll = 0
          suitableDataList.forEach(({ theAmount, commissionAmount,totalAmount,paidAmount,commissionAmountRule }) => {
            theAmountAll += parseFloat(theAmount);
            commissionAmountAll += parseFloat(commissionAmount);
            totalAmountAll += parseFloat(totalAmount);
            paidAmountAll += parseFloat(paidAmount);
            commissionAmountRuleAll += parseFloat(commissionAmountRule);
          });
            theAmountAll =  Math.round(parseFloat(theAmountAll)*100)/100
            commissionAmountAll = Math.round(parseFloat(commissionAmountAll)*100)/100
            totalAmountAll =  Math.round(parseFloat(totalAmountAll)*100)/100
            paidAmountAll =  Math.round(parseFloat(paidAmountAll)*100)/100
            commissionAmountRuleAll =  Math.round(parseFloat(commissionAmountRuleAll)*100)/100
          let obj ={
            theAmount: theAmountAll,
            commissionAmount: commissionAmountAll,
            totalAmount: totalAmountAll,
            paidAmount: paidAmountAll,
            commissionAmountRule: commissionAmountRuleAll,
            houseArea: '合计',
            id: 999
          }
          suitableDataList.push(obj)
        }

        let params = {
          applyDetailTemId: applyDetailTemIdList,
          applyIdList: detail.applyIdList,
          ruleName: detail.ruleName,
        }
        const { success, msg, data } = yield call(ondelete, {...params})
        if(success){
          message.warn('删除成功')

        }
      },
      *againdelete({payload},{put,select,call}){
        //重选操作
        let {channelIndex} = yield select(state => state[tmpModule.namespace])
        let arr = []
        arr.push(payload.id)
        let params = {
          applyDetailTemId: arr,
        }
        const { success, msg, data } = yield call(ondelete, {...params})
        if(success){
          message.warn('重选成功')
          channelIndex = "1"
          yield put({type: 'updateStore',payload: {channelIndex}})
          yield put({type: 'queryApplyDetailLm', payload: {}})
        }
      },
      *save({payload},{put,select,call}){
        //保存
        let {aurList,detail,createFaymentMethodFlag } = yield select(state => state[tmpModule.namespace])
        if(!createFaymentMethodFlag){
          message.warn('请先生成佣金明细')
          return false
        }
        detail.aur = aurList
        let params = detail
        if(!params.id){
          //不包含ID为录入
          const { success, msg, data } = yield call(save, {...params})
          if(success){
            message.success('保存成功')
            hashHistory.push({
              pathname: '/home/commissions/commissionsDistList',
              query: {}
            })
          }
        }else{
          //包含Id为编辑
          const { success, msg, data } = yield call(save, {...params})
          if(success){
            message.success('修改成功')
            hashHistory.push({
              pathname: '/home/commissions/commissionsDistList',
              query: {}
            })
          }
        }
      },
      *down({payload}, {put, call, select}) {
          let {noSuitableDataList,suitableDataList,channelIndex,detail,createFaymentMethodFlag} = yield select(state => state[tmpModule.namespace])
          if(!createFaymentMethodFlag){
            message.warn('请先生成佣金明细')
            return false
          }
          let arr = []
          for(var item of suitableDataList){
            if(item.houseArea != '合计') {
              arr.push(item)
            }
          }
          let params
          if(channelIndex == '1'){
            params = arr
          }else{
            params = noSuitableDataList
          }
          const {data, success} = yield call(down,params)
          if (success) {
            var $a = $("<a>");
            $a.attr("href", data.href);
            $a.attr("download", '佣金明细客户信息');
            $("body").append($a);
            $a[0].click();
            $a.remove();
            message.success('导出成功,正在为您下载表格')
          }
      },
      *searchAccountingName({payload}, {put, call, select}) {
        let {distributionNameList,detail} = yield select(state => state[tmpModule.namespace])
        let params = {
            projectId: detail.projectId
        }
        const {data, success} = yield call(searchAccountingName,params)
        if(success){
          distributionNameList = data
          yield put({
            type: 'updateStore',
            payload: {
              distributionNameList
            }
          })
        }
      },
      //查询联名客户
      *queryApplyDetailLm({payload}, {put, call, select}) {
        //生成客户明细
        let {buyHouseModalObj,jointData,applyDetailTemIdList,createFaymentMethodFlag,selectedRowKeys,selectedRows,funType,checkboxData,channelIndex,noSuitableDataList,suitableDataList,detail,tableData} = yield select(state => state[tmpModule.namespace])
        let tempArr = []
        let paymentMethod = []
        checkboxData.paymentTypeName.forEach(item => {
          let obj = {
            id:'',
            applyId:'',
          }
          if(item == 'SD040201'){
            obj['paymentTypeCode'] = 'SD040201'
            obj['paymentTypeName'] = '一次性付款'
            obj['paymentRatioNum'] = checkboxData.oneTime
          }else if(item == 'SD040205'){
            obj['paymentTypeCode'] = 'SD040205'
            obj['paymentTypeName'] = '混合贷款'
            obj['paymentRatioNum'] = checkboxData.hybrid
          }else if(item == 'SD040208'){
            obj['paymentTypeCode'] = 'SD040208'
            obj['paymentTypeName'] = '非员工首付分期'
            obj['paymentRatioNum'] = checkboxData.noStaff
          }else if(item == 'SD040203'){
            obj['paymentTypeCode'] = 'SD040203'
            obj['paymentTypeName'] = '商业贷款'
            obj['paymentRatioNum'] = checkboxData.business
          }else if(item == 'SD040204'){
            obj['paymentTypeCode'] = 'SD040204'
            obj['paymentTypeName'] = '公积金按揭'
            obj['paymentRatioNum'] = checkboxData.reserve
          }else if(item == 'SD040207'){
            obj['paymentTypeCode'] = 'SD040207'
            obj['paymentTypeName'] = '非员工全款分期'
            obj['paymentRatioNum'] = checkboxData.noStaffAll
          }
          tempArr.push(obj)
        });
        paymentMethod = detail.paymentMethod?detail.paymentMethod:[]
        for(var item of paymentMethod){
          for(var itemed of tempArr){
            if(item.paymentTypeCode == itemed.paymentTypeCode){
              itemed.id = item.id
              itemed.applyId = item.applyId
            }
          }
        }
        let params = {
          projectId: detail.projectId,
          distCoId: detail.distCoId,
          ruleId: detail.ruleId,
          accountingId: detail.accountingId,
          //  applyId: detail.applyId,
          applyIdList: detail.applyIdList,
          ruleName: detail.ruleName,
          computeNodes: detail.computeNodes,
          buyState: detail.buyState,
          applyDetailTemId: [],
          endTime: detail.endTime,
          PaymentMethod: tempArr,
          distCoName: detail.distCoName,
          noCommission: detail.noCommission,
          id: detail.id,
        }
        const {data, success} = yield call(queryApplyDetailLm,params)
        if(success){
          if(data&&data.listLm&&data.listLm.length){
            jointData = data.listLm
            buyHouseModalObj.visible  = !buyHouseModalObj.visible
          }else{
            yield put({type: 'create', payload: {}})
          }
          yield put({
            type: 'updateStore',
            payload: {
              jointData,buyHouseModalObj
            }
          })
        }
      },
      // 重选联名购房
      *lmReChooseList({payload}, {put, call, select}) {
        let {buyHouseModalObj,againJointData,applyDetailTemIdList,createFaymentMethodFlag,selectedRowKeys,selectedRows,funType,checkboxData,channelIndex,noSuitableDataList,suitableDataList,detail,tableData} = yield select(state => state[tmpModule.namespace])
        let tempArr = []
        let paymentMethod = []
        checkboxData.paymentTypeName.forEach(item => {
          let obj = {
            id:'',
            applyId:'',
          }
          if(item == 'SD040201'){
            obj['paymentTypeCode'] = 'SD040201'
            obj['paymentTypeName'] = '一次性付款'
            obj['paymentRatioNum'] = checkboxData.oneTime
          }else if(item == 'SD040205'){
            obj['paymentTypeCode'] = 'SD040205'
            obj['paymentTypeName'] = '混合贷款'
            obj['paymentRatioNum'] = checkboxData.hybrid
          }else if(item == 'SD040208'){
            obj['paymentTypeCode'] = 'SD040208'
            obj['paymentTypeName'] = '非员工首付分期'
            obj['paymentRatioNum'] = checkboxData.noStaff
          }else if(item == 'SD040203'){
            obj['paymentTypeCode'] = 'SD040203'
            obj['paymentTypeName'] = '商业贷款'
            obj['paymentRatioNum'] = checkboxData.business
          }else if(item == 'SD040204'){
            obj['paymentTypeCode'] = 'SD040204'
            obj['paymentTypeName'] = '公积金按揭'
            obj['paymentRatioNum'] = checkboxData.reserve
          }else if(item == 'SD040207'){
            obj['paymentTypeCode'] = 'SD040207'
            obj['paymentTypeName'] = '非员工全款分期'
            obj['paymentRatioNum'] = checkboxData.noStaffAll
          }
          tempArr.push(obj)
        });
        paymentMethod = detail.paymentMethod
        for(var item of paymentMethod){
          for(var itemed of tempArr){
            if(item.paymentTypeCode == itemed.paymentTypeCode){
              itemed.id = item.id
              itemed.applyId = item.applyId
            }
          }
        }
        let params = {
          projectId: detail.projectId,
          distCoId: detail.distCoId,
          ruleId: detail.ruleId,
          accountingId: detail.accountingId,
          //  applyId: detail.applyId,
          applyIdList: detail.applyIdList,
          ruleName: detail.ruleName,
          computeNodes: detail.computeNodes,
          buyState: detail.buyState,
          applyDetailTemId: [],
          endTime: detail.endTime,
          PaymentMethod: tempArr,
          distCoName: detail.distCoName,
          noCommission: detail.noCommission,
          id: detail.id,
        }
        const {data, success} = yield call(lmReChooseList,params)
        if(success){
          againJointData = data.listLm
          yield put({type: 'updateStore',payload: {againJointData}})
        }
      },
      *saveLmHandleUnionBuy({payload}, {put, call, select}) {
        let {jointData} = yield select(state => state[tmpModule.namespace])
        let params = {
          listLm: jointData
        }
        const {success} = yield call(saveLmHandleUnionBuy,params)
        if(success){
          message.warn('确认成功')
          yield put({type: 'create', payload: {}})
        }
      },

      *queryLmDetail({payload}, {put, call, select}) {
        let {buyHouseInfo,houseInfoData} = yield select(state => state[tmpModule.namespace])
        let params = {
          transactionId: payload.id
        }
        const {success,data} = yield call(queryLmDetail,params)
        if(success){
          houseInfoData = data
          buyHouseInfo.visible = !buyHouseInfo.visible
          yield put({
            type: 'updateStore',
            payload: {
              houseInfoData,buyHouseInfo
            }
          })
        }
      },
      *queryCheckOut({payload}, {put, call, select}) {
        let {detail} = yield select(state => state[tmpModule.namespace])
        let params = {
          applyDetail: detail.applyDetail
        }
        const {rows, success} = yield call(queryCheckOut,params)
        if(success){
          if(rows&&rows.length){
            let tips = ''
            for(var item of rows){
              tips += item.fullName + ','
            }
            tips = tips.substring(0, tips.length - 1);
            message.warn('以下房间' + tips + '已退房，请重新生成房源明细')
          }else{
            yield put({type: 'save', payload: {}})
          }
        }
      },
      *queryClueByClueId({payload}, {put, call, select}) {
        let {cluesUpModalObj} = yield select(state => state[tmpModule.namespace])
        let params = {
          clueId: payload.data.clueId
        }
        const {data, success} = yield call(queryClueByClueId,params)
        if(success){
          cluesUpModalObj.data = data
          yield put({type: 'updateStore', payload: {cluesUpModalObj}})
        }
      },
      *projectFilter({payload}, {put, call, select}) {
        let {projectFilterParams} = yield select(state => state[tmpModule.namespace])
       
        const {rows, success} = yield call(projectFilter)
        if(success){
          projectFilterParams = rows
          yield put({
            type: 'updateStore',
            payload: {
              projectFilterParams
            }
          })
        }
      },

      *getMcrmAdmin({payload}, {put, call, select}) {
        
        let {riskId} = yield select(state => state[tmpModule.namespace])
        if(!riskId){
          message.warn('该条数据没有对应的风控详情')
          return false
        }
        // let riskId = '03f2f6f5-4b4f-40ca-ac47-7c729407b816'
        // let params = {
        // "username":"mdzy_msfs",
        // "password":"Abcd2018"
        // }
        // const {tokenId, flag} = yield call(getMcrmAdmin,params)
        // if(flag){
          // if(tokenId){
            // let url = `http://112.74.60.235/mcrm-admin/a/risk/riskDistinguish/form?id=${riskId}`
            let url = ''
            if(config.ENV === 'prod'){
              url = `https://ms-admin.mideazy.com/mcrm-admin/a/risk/riskDistinguish/form?id=${riskId}`
            }else{
              url = `http://112.74.60.235/mcrm-admin/a/risk/riskDistinguish/form?id=${riskId}`
            }
            window.open(url)
          // }
        // }
      },
      * importAccount ({payload}, {put, call, select}) {
        let {channelIndex,detail,noSuitableDataList,suitableDataList,tableData,uploadFileObj, imageUrls1} = yield select(state => state[tmpModule.namespace])
        let fileUrl = imageUrls1[0] && imageUrls1[0].url || ''
        let fileName = imageUrls1[0] && imageUrls1[0].name || ''
        if (!fileUrl) {
          message.error('请上传文件')
          return false
        }
       
        uploadFileObj.loading = true
        yield put({type: 'updateStore', payload: {uploadFileObj}})
        let params = {
          fileUrl:fileUrl,
          applyDetail: detail.applyDetail
        }
        const {data, success, msg} = yield call(importAccount, {...params})
        if (success === true) {

          suitableDataList = []
          noSuitableDataList = []
          if(!data.applyDetail){
            message.error('导入失败')
            return false
          }
          let tempList = data.applyDetail
          for(var item of tempList){
            if(item.acState == '1'){
              suitableDataList.push(item)
             }else{
               noSuitableDataList.push(item)
             }
          }
          if(suitableDataList.length>0){
            let theAmountAll = 0;
            let commissionAmountAll = 0;
            let totalAmountAll = 0;
            let paidAmountAll = 0;
            let commissionAmountRuleAll = 0
            suitableDataList.forEach(({ theAmount, commissionAmount,totalAmount,paidAmount,commissionAmountRule }) => {
              theAmountAll += parseFloat(theAmount);
              commissionAmountAll += parseFloat(commissionAmount);
              totalAmountAll += parseFloat(totalAmount);
              paidAmountAll += parseFloat(paidAmount);
              commissionAmountRuleAll += parseFloat(commissionAmountRule);
            });
            theAmountAll =  Math.round(parseFloat(theAmountAll)*100)/100
            commissionAmountAll = Math.round(parseFloat(commissionAmountAll)*100)/100
            totalAmountAll =  Math.round(parseFloat(totalAmountAll)*100)/100
            paidAmountAll =  Math.round(parseFloat(paidAmountAll)*100)/100
            commissionAmountRuleAll =  Math.round(parseFloat(commissionAmountRuleAll)*100)/100
            let obj ={
              theAmount: theAmountAll,
              commissionAmount: commissionAmountAll,
              totalAmount: totalAmountAll,
              paidAmount: paidAmountAll,
              commissionAmountRule: commissionAmountRuleAll,
              houseArea: '合计',
              id: 999
            }
            suitableDataList.push(obj)
          }
           if(channelIndex == '1'){
             tableData.dataSource = suitableDataList
           }else{
             tableData.dataSource = noSuitableDataList
           }
          detail.applyDetail = tempList
          yield put({
            type: 'updateStore',
            payload: {
              detail,noSuitableDataList,suitableDataList,tableData
            }
          })
          message.success('操作成功')
        }
        uploadFileObj.visible = false
        uploadFileObj.loading = false
      },
      * selectedKeysChange ({payload}, {put, select, call}) {
        let {selectedRowKeys,selectedRows} = yield select(state => state[tmpModule.namespace])
        
        selectedRowKeys=payload.selectedRowKeys
        selectedRows=payload.selectedRows
        yield put({
          type: 'updateStore',
          payload: {
            selectedRowKeys,selectedRows
          }
        })
      },
      * selectedKeysChange1 ({payload}, {put, select, call}) {
        let {selectedRowKeys1,selectedRows1} = yield select(state => state[tmpModule.namespace])
        selectedRowKeys1=payload.selectedRowKeys
        selectedRows1=payload.selectedRows
        yield put({
          type: 'updateStore',
          payload: {
            selectedRowKeys1,selectedRows1
          }
        })
      },
    },
    // 存入状态机
    reducers: {
      updateStore(preState, action) {
        return Object.assign({}, preState, action.payload)
      },
    }
  }
  
  export default tmpModule
  